import Vue from 'vue'
import VueRouter from 'vue-router'
import { getItem } from '@/utils/auth.js'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
const Login = () => import('@/views/login')
const Home = () => import('@/views/home')
const Layout = () => import('@/views/layout')
const Article = () => import('@/views/article')
const Publish = () => import('@/views/publish')
// 1:pagkage,json   2.index.js  3:index.vue
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: Home
      },
      {
        path: '/article',
        component: Article
      },
      {
        path: '/publish',
        component: Publish
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 导航前置守卫
router.beforeEach((to, from, next) => {
  Nprogress.start()
  // 有token 可以正常登录页
  if (getItem()) {
    if (to.path.toLowerCase() === '/login') {
      // 直接跳转到首页
      next('/home')
    } else {
      // 如果要去页面不是登陆页可以正常进入
      // 限制回登录页
      next()
    }
  } else {
    // 如果没有token 只能回login页面
    if (to.path.toLowerCase() === '/login') {
      // 要回login页面可以正常进入
      next()
    } else {
      // 如果要去的页面不是login页面，跳转回至登录页面
      next('/login')
    }
  }
})

// 导航后置守卫
router.afterEach((to, form) => {
  Nprogress.done()
  // console.log(to, form)
})

const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
